package controller;

import model.IExchangerModel;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import view.IExchangerView;

public class CurrenciesHandler extends DefaultHandler {
	private IExchangerModel model;
	private IExchangerView view; //? Utile?

	private String currencyName;
	private String code;
	private double rate;
	private String iconPath;

	private StringBuffer buffer;

	// simple constructeur
	public CurrenciesHandler(IExchangerModel model, IExchangerView view) {
		super();
		this.model = model;
		this.view = view;
	}

	// detection d'ouverture de balise
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if(qName.equals("icon") && attributes.getQName(0).equals("src")){
			iconPath = attributes.getValue(0);
		}
		else{
			buffer = new StringBuffer();
//			if (!qName.equals("currencies")&& !qName.equals("currency")  && !qName.equals("name")
//					&& !qName.equals("code") && !qName.equals("rate")
//					&& !qName.equals("icon"))
//				view.showErrorMessageDialog("unknowTag");
		}
	}

	// detection fin de balise
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if (qName.equals("currency")) {
			model.addCurrency(currencyName, code, rate, iconPath );
			currencyName = null;
			code = null;
			rate = 0;
			iconPath = null;
			buffer = null;
		} else if (qName.equals("name")) {
			currencyName = buffer.toString();
			buffer = null;
		} else if (qName.equals("code")) {
			code = buffer.toString();
			buffer = null;
		} else if (qName.equals("rate")) {
			rate = Double.parseDouble(buffer.toString());
			buffer = null;
		} 
//		else if (!qName.equals("currencies")) {
//			view.showErrorMessageDialog("unknowTag");
//		}
	}

	// detection de caracteres
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String lecture = new String(ch, start, length);
		if (buffer != null)
			buffer.append(lecture);
	}
}
